define [
	'jquery'
	'sammy/plugins/sammy.template-0.7.1.min.js'
	'jquery.couch.js'
	'helper'
], ($, undef, undef, H) ->
	$.fn.mb_search = (S) ->
		$this = $(@)
		$this.find('input:submit').after('<input type="checkbox"/>Instant')
		
		$('[name="search_term"]').on "keyup", ->
			return if not $this.find('input:checkbox').is(':checked')
			return if $(@).val().length <= 3
			$this.find('input:submit').click()
		
		$(@).find('input:submit').on 'click', ->
			
			# Lower case the query key for couchdb and parse through PostalCode and Phone format 
			_query = $('[name="search_term"]').val().toLowerCase().isPostal().isPhone()
			_unparsed_query = $('[name="search_term"]').val()

			
			# If the query is in format LASTNAME, FIRSTNAME.. remove the space after the comma to match the indexing
			(_query = _query.replace(/[ ]/g, '') if _query.charAt(i+1) is " " ) if (i = _query.indexOf(',')) isnt 0
					
			arg = [
				search_term: _query,
				raw_term: _unparsed_query,
				search_type: $('input:checked').val().toLowerCase()
				]
			
			$.publish "mb.query", arg
			return false
		return @
	return
